package com.cloud.auth.service.impl;

import com.cloud.auth.mapper.BaseMapper;
import com.cloud.auth.mapper.UserRoleMapper;
import com.cloud.auth.service.UserRoleService;
import com.cloud.auth.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @packageName: com.api.service.auth.impl
 * @name: UserRoleServiceImpl
 * @description:
 * @author: 董定卓
 * @dateTime: 2019/6/13 17:44
 */
@Service("userRoleService")
public class UserRoleServiceImpl extends BaseServiceImpl implements UserRoleService {

    @Autowired
    UserRoleMapper mapper;

    @Override
    protected BaseMapper getMapper() {
        return mapper;
    }

    @Override
    @Transactional
    public int add(Map<String, Object> map) {
        int i = mapper.delete(map);
        String userId = map.get("userId").toString();
        String roleIdStr = MapUtil.getString(map, "roleIds");
        if (roleIdStr != null) {
            String[] roleIds = roleIdStr.split(",");
            if (roleIds.length > 0) {
                List<Map<String, Object>> list = new ArrayList<>();
                Map<String, Object> paramMap = null;
                for (String roleId : roleIds) {
                    paramMap = new HashMap<>();
                    paramMap.put("userId", userId);
                    paramMap.put("roleId", roleId);
                    list.add(paramMap);
                }
                i += mapper.insertBatch(list);
            }
        }
        return i;
    }

    /**
     * 获取用户角色
     *
     * @param map
     * @return
     */
    @Override
    public List<String> ownRole(Map<String, Object> map) {
        return mapper.ownRole(map);
    }
}
